package com.scud.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.scud.common.utils.JwtUtil;
import com.scud.gateway.properties.ExcludeProperties;
import com.scud.model.system.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Map;


/**
 * @author vermouth
 */
@Component
public class JwtFilter implements WebFilter {

    @Autowired
    private ExcludeProperties excludeProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Autowired
    ServerSecurityContextRepository serverSecurityContextRepository;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (isExclude(request.getPath().toString())) {
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().get("token").get(0);
        if (token==null){
            //放行
            return chain.filter(exchange);
        }
        System.out.println(token);
        //解析token,放入springSecurity的上下文当中
        Map<String, Object> claims = null;
        try{
            claims=JwtUtil.parseJWT("scud",token);
        }catch (Exception e){
            response.setStatusCode(HttpStatusCode.valueOf(401));
            e.printStackTrace();
//            throw new Exception(e);
        }

        //获取用户id
        Long userId = Long.valueOf(claims.get("user_id").toString());
        User user = User.builder()
                .id(userId)
                .build();
        String json = JSON.toJSONString(user);
        Authentication authentication=new UsernamePasswordAuthenticationToken(json,null,null);

        SecurityContextImpl securityContext = new SecurityContextImpl(authentication);
        return serverSecurityContextRepository.save(exchange,securityContext)
                .then(chain.filter(exchange));
    }

    private boolean isExclude(String path) {
        for (String ignoreUrl : excludeProperties.getIgnoreUrls()) {
            if (antPathMatcher.match(ignoreUrl, path)) {
                return true;
            }
        }
        return false;
    }
}
